package com.ck.ips.service.impl.sys;

import com.ck.common.model.Department;
import com.ck.common.model.OperationResult;
import com.ck.common.page.PageInfo;
import com.ck.core.constant.BusinessConstant;
import com.ck.core.constant.OperationType;
import com.ck.core.constant.PageConstant;
import com.ck.core.constant.SymbolConstant;
import com.ck.core.context.UserContextHolder;
import com.ck.core.util.TreeUtils;
import com.ck.ips.dao.sys.DepartmentMapper;
import com.ck.ips.model.dto.sys.DepartmentTreeDTO;
import com.ck.ips.model.vo.sys.DepartmentListVO;
import com.ck.ips.model.vo.sys.DepartmentSelectListVO;
import com.ck.ips.service.sys.DepartmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 部门Service实现类
 *
 */
@Service(value = "departmentService")
public class DepartmentServiceImpl implements DepartmentService {

	@Autowired
	private DepartmentMapper departmentMapper;
	/** 部门名称最大长度 */
	private final int MAX_DEPARTMENT_NAME_LENGTH = 16;
	/**
	 * 保存部门
	 *
	 * @param department Department
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult insertDepartment(Department department) {
		department.setDepartmentId(null);
		if (StringUtils.isBlank(department.getDepartmentName())) {
			return OperationResult.newValidateFailOperationResult("部门名称不能为空");
		}
		if ( department.getDepartmentName().length() > MAX_DEPARTMENT_NAME_LENGTH) {
			return OperationResult.newValidateFailOperationResult("部门名称长度不能超过"+ MAX_DEPARTMENT_NAME_LENGTH +"位");
		}
		if ( department.getStatus() == null ) {
			return OperationResult.newValidateFailOperationResult("部门启用/禁用状态不能为空");
		}

		Department departmentByName = departmentMapper.getByDepartmentName(department.getDepartmentName());
		if ( departmentByName != null ) {
			return OperationResult.newValidateFailOperationResult("该部门名称已存在");
		}
		department.setAddTime(System.currentTimeMillis());
		department.setOperator(UserContextHolder.currentUser().getUserName());
		departmentMapper.insertDepartment(department);
		return OperationResult.newSuccessTipsOperationResult("新增部门：" + department.getDepartmentName());
	}

	/**
	 * 修改部门
	 *
	 * @param department Department
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult updateDepartment(Department department) {
		if (StringUtils.isBlank(department.getDepartmentName())) {
			return OperationResult.newValidateFailOperationResult("部门名称不能为空");
		}
		if ( department.getDepartmentName().length() > MAX_DEPARTMENT_NAME_LENGTH) {
			return OperationResult.newValidateFailOperationResult("部门名称长度不能超过"+ MAX_DEPARTMENT_NAME_LENGTH +"位");
		}
		if ( department.getDepartmentId() == null ) {
			return OperationResult.newValidateFailOperationResult("部门id不能为空");
		}
		if ( department.getStatus() == null ) {
			return OperationResult.newValidateFailOperationResult("部门启用/禁用状态不能为空");
		}
		if ( department.getParentId() != null ) {
			String childIds = departmentMapper.getChildIds(department.getDepartmentId());
			if ( Arrays.asList(childIds.split(SymbolConstant.COMMA_EN)).contains(department.getParentId().toString()) ) {
				return OperationResult.newValidateFailOperationResult("父级部门不能为当前部门及其子级部门");
			}
		}
		Department oldDepartment = departmentMapper.getDepartmentById(department.getDepartmentId());
		if ( oldDepartment == null ) {
			return OperationResult.newValidateFailOperationResult("未找到相应部门信息");
		}
		Department departmentByName = departmentMapper.getByDepartmentName(department.getDepartmentName());
		if ( departmentByName != null && !departmentByName.getDepartmentId().equals(oldDepartment.getDepartmentId()) ) {
			return OperationResult.newValidateFailOperationResult("该部门名称已存在");
		}

		// 修改状态
		if ( !oldDepartment.getStatus().equals(department.getStatus()) ) {
			enableDisableDepartment(department.getDepartmentId(),department.getStatus());
		}

		department.setUpdateTime(System.currentTimeMillis());
		department.setOperator(UserContextHolder.currentUser().getUserName());
		departmentMapper.updateDepartment(department);
		return OperationResult.newSuccessTipsOperationResult("修改部门："+department.getDepartmentName());
	}

	/**
	 * 通过部门ID获取部门
	 *
	 * @param departmentId 部门ID
	 * @return Department
	 */
	@Override
	public Department getDepartmentById(Long departmentId) {
		return departmentMapper.getDepartmentById(departmentId);
	}

	/**
	 * 部门列表
	 *
	 * @param status         状态
	 * @param departmentName 部门名称
	 * @return Page<DepartmentListVO>
	 */
	@Override
	public PageInfo<DepartmentListVO> listDepartment(Integer status, String departmentName, Integer pageNum, Integer pageSize) {
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<DepartmentListVO> page = departmentMapper.listDepartment(status, departmentName);
		return PageInfo.convert(page);
	}

	/**
	 * 获取所有启用的部门
	 *
	 * @return List<DepartmentSelectListVO>
	 */
	@Override
	public List<DepartmentSelectListVO> listDepartmentSelect()  {
		return departmentMapper.listDepartmentSelect(BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取部门树列表
	 *
	 * @return List<DepartmentTreeDTO>
	 * @throws ServerException
	 */
	@Override
	public List<DepartmentTreeDTO> listDepartmentTree(){
		List<DepartmentTreeDTO> departmentTreeList = departmentMapper.listDepartmentTree(BusinessConstant.STATUS_ENABLE);
		if (CollectionUtils.isNotEmpty(departmentTreeList)) {
			return TreeUtils.getTreeList(departmentTreeList);
		}
		return new ArrayList<>();
	}

	/**
	 * 禁用启用部门
	 * @param originStatus 状态
	 * @param departmentId 待操作的部门Id
	 * @author linqiang
	 */
	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult enableDisableDepartment(Long departmentId,Integer originStatus) {
		if ( departmentId == null || originStatus == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要操作的部门");
		}
		Department oldDepartment = departmentMapper.getDepartmentById(departmentId);
		if ( oldDepartment == null ) {
			return OperationResult.newValidateFailOperationResult("要操作的部门不存在");
		}

		int status = BusinessConstant.STATUS_DISABLE;
		int queryStatus = BusinessConstant.STATUS_DISABLE;
		String tips = "";
		if (OperationType.DISABLE_DEPARTMENT.getValue().equals(originStatus)) {
			tips = "禁用部门：" + oldDepartment.getDepartmentName();

			//禁用
			queryStatus = BusinessConstant.STATUS_ENABLE;
		} else if (OperationType.ENABLE_DEPARTMENT.getValue().equals(originStatus)) {
			tips = "启用部门：" + oldDepartment.getDepartmentName();
			//启用
			status = BusinessConstant.STATUS_ENABLE;
		}

		//所有子部门
		List<Long> childrenId = new ArrayList<>();
		List<DepartmentSelectListVO> departmentSelectListVOS = departmentMapper.listDepartmentSelect( queryStatus ) ;
		childrenId = getChildIdList(childrenId, departmentSelectListVOS, departmentId);
		if(CollectionUtils.isNotEmpty(childrenId)){
			departmentMapper.batchEnableDisable(childrenId, status);
		}

		oldDepartment.setUpdateTime(System.currentTimeMillis());
		oldDepartment.setStatus(originStatus);
		departmentMapper.updateDepartment(oldDepartment);

		return OperationResult.newSuccessTipsOperationResult(tips);
	}

	@Override
	@Transactional( rollbackFor = Exception.class)
	public OperationResult deleteDepartment(Long departmentId) {
		if ( departmentId == null ) {
			return OperationResult.newValidateFailOperationResult("请选择要删除的部门");
		}
		Department oldDepartment = departmentMapper.getDepartmentById(departmentId);
		if ( oldDepartment == null  ) {
			return OperationResult.newValidateFailOperationResult("操作的部门数据不存在");
		}
		String childIds = departmentMapper.getChildIds(departmentId);
		if ( childIds.split(SymbolConstant.COMMA_EN).length > 1 ) {
			return OperationResult.newValidateFailOperationResult("该部门拥有子部门，请先删除子部门");
		}
		String userIdsByDepartmentId = departmentMapper.getUserIdsByDepartmentId(departmentId);
		if ( !StringUtils.isBlank(userIdsByDepartmentId) ) {
			return OperationResult.newValidateFailOperationResult("该部门下拥有员工，请先解除员工关系");
		}
		departmentMapper.deleteDepartment(departmentId);
		return OperationResult.newSuccessTipsOperationResult("删除部门：" +oldDepartment.getDepartmentName());
	}


	private List<Long> getChildIdList(List<Long> childIdList, List<DepartmentSelectListVO> all, Long pid){
		for(DepartmentSelectListVO mu: all){
			//遍历出父id等于参数的id，add进子节点集合
			if(mu.getParentId() != null && mu.getParentId().equals(pid)){
				//递归遍历下一级
				getChildIdList(childIdList,all,mu.getDepartmentId());
				childIdList.add(mu.getDepartmentId());
			}
		}
		return childIdList;
	}
}
